<?php
/**
 *   OPENSHOP 尺码属性相关设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: size.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php');
$exc = new exchange($os->table('size'),$db,'size_id','size_name');

/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

if($_REQUEST['act']=='list')
{	
	//检查权限
	admin_priv();
		
	$smarty->assign('ur_here',      '商品尺码');  
	$smarty->assign('action_link',  array('href' => 'size.php?act=add', 'text' => '添加尺码'));
	$smarty->assign('full_page',    1);
	$size_list = get_sizelist();
	$smarty->assign('size_list',    $size_list['size']);
    $smarty->assign('filter',       $size_list['filter']);
    $smarty->assign('record_count', $size_list['record_count']);
    $smarty->assign('page_count',   $size_list['page_count']);	

    assign_query_info();
	$smarty->display('size_list.tpl');	
}
elseif($_REQUEST['act']=='add')
{
	/* 权限检查 */
    admin_priv('add_size');
    
    $smarty->assign('ur_here',      '添加尺码');  
	$smarty->assign('action_link',  array('href' => 'size.php?act=list', 'text' => '尺码管理'));
	$smarty->assign('form_act',     'insert');
	
	assign_query_info();	
	$smarty->display('size_info.tpl');		
}
elseif($_REQUEST['act']=='insert')
{
	/* 权限检查 */
    admin_priv('add_size');	
    
    $is_only = $exc->is_only('size_name', $_POST['size_name']);
    if (!$is_only)
    {
        sys_msg(sprintf('尺码名称 %s 已经存在！', stripslashes($_POST['size_name'])), 1);
    }
    $is_only = $exc->is_only('size_code', $_POST['size_code']);
    if (!$is_only)
    {
        sys_msg(sprintf('尺码代码 %s 已经存在！', stripslashes($_POST['size_code'])), 1);
    }
    
    /*插入数据*/
    $sql = "INSERT INTO ".$os->table('size')." VALUES (null, '$_POST[size_code]', '$_POST[size_name]', '$_POST[size_note]')";
    $db->query($sql);

    admin_log($_POST['size_name'],'add','size');  
    
    /* 清除缓存 */
    clear_cache_files();      
    /*添加链接*/
    $link[0]['text'] = '继续添加尺码';
    $link[0]['href'] = 'size.php?act=add';

    $link[1]['text'] = '返回尺码列表';
    $link[1]['href'] = 'size.php?act=list';

    sys_msg('新尺码添加成功！', 0, $link);	
}
elseif($_REQUEST['act']=='edit')
{
    /* 权限判断 */
    admin_priv('edit_size');
    
    $sql = "SELECT size_id, size_code, size_name, size_note "."FROM " .
           $os->table('size'). " WHERE size_id='$_REQUEST[size_id]'";
    $size = $db->GetRow($sql);

    $smarty->assign('ur_here',     '编辑尺码记录');
    $smarty->assign('action_link', array('text' => '尺码管理', 'href' => 'size.php?act=list&' . list_link_postfix()));
    $smarty->assign('size',       $size);
    $smarty->assign('form_act', 'updata');

    assign_query_info();	
	$smarty->display('size_info.tpl');	
}
elseif($_REQUEST['act']=='updata')
{
	/* 权限判断 */
	admin_priv('edit_size');
	
    if ($_POST['size_name'] != $_POST['old_size_name'])
    {
        /*检查尺码名是否相同*/
        $is_only = $exc->is_only('size_name', $_POST['size_name'], $_POST['size_id']);

        if (!$is_only)
        {
            sys_msg(sprintf('尺码名称 %s 已经存在！', stripslashes($_POST['size_name'])), 1);
        }
    }
    if ($_POST['size_code'] != $_POST['old_size_code'])
    {
        /*检查颜色代码是否相同*/
        $is_only = $exc->is_only('size_code', $_POST['size_code'], $_POST['size_id']);

        if (!$is_only)
        {
            sys_msg(sprintf('尺码代码 %s 已经存在！', stripslashes($_POST['size_code'])), 1);
        }
    } 
	$param = "size_code = '$_POST[size_code]',  size_name='$_POST[size_name]', size_note='$_POST[size_note]' ";
    if ($exc->edit($param,  $_POST['size_id']))
    {
        /* 清除缓存 */
        clear_cache_files();

        admin_log($_POST['size_name'], 'edit', 'size');

        $link[0]['text'] = '返回尺码列表';
        $link[0]['href'] = 'size.php?act=list&' . list_link_postfix();
        $note = vsprintf('尺码 %s 修改成功！', $_POST['size_name']);
        sys_msg($note, 0, $link);
    }
    else
    {
        die($db->error());
    }
}
elseif ($_REQUEST['act'] == 'remove')
{
	/* 权限判断 */
	admin_priv('drop_size');

    $size_id = intval($_GET['id']);

    $size_name = $db->getOne('SELECT size_name FROM ' .$os->table('size'). " WHERE size_id='$size_id'");
    
    $cat_rel_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('category_size'). " WHERE size_id='$size_id'");
    
    $goods_rel_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('goods_size'). " WHERE size_id='$size_id'");
    
    if($cat_rel_count==0 && $goods_rel_count==0){
	    /* 删除该尺码 */
	    if($exc->drop($size_id)){
			admin_log($size_name, 'remove', 'size');	    	
	    }
    }else{
    	make_json_error('"'.$size_name .'" 该尺码与商品、分类还有关联,您不能删除!');
    }
    
    $url = 'size.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
    os_header("Location: $url\n");
    exit;
}
elseif ($_REQUEST['act'] == 'query')
{
    $size_list = get_sizelist();
    $smarty->assign('size_list',    $size_list['size']);
    $smarty->assign('filter',       $size_list['filter']);
    $smarty->assign('record_count', $size_list['record_count']);
    $smarty->assign('page_count',   $size_list['page_count']);

    make_json_result($smarty->fetch('size_list.tpl'), '',
        array('filter' => $size_list['filter'], 'page_count' => $size_list['page_count']));
}
elseif($_REQUEST['act']=='relevancy')
{
	/* 权限检查 */
    admin_priv('relevancy_cat_size');	
    
    $smarty->assign('ur_here',      '关联设置'); 
	$smarty->assign('action_link',  array('href' => 'size.php?act=list', 'text' => '尺码管理'));
	$size_id = $db->getOne("SELECT size_id FROM ".$os->table('size').
	             " WHERE size_id=".intval($_GET['size_id']));
	$smarty->assign('cat_size_list',get_cat_sizelist(intval($_GET['size_id'])));
	$smarty->assign('size_id',$size_id);
	assign_query_info();
	
	$smarty->display('size_relevancy.tpl');	
}elseif ($_REQUEST['act']=='search_cat'){
    /* 检查权限 */
    check_authz_json('relevancy_cat_size');

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword);	
    $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $os->table('category') .
        " WHERE cat_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
    $arr = $db->getAll($sql);
    if (empty($arr))
    {
        $arr = array(0 => array(
            'id'   => 0,
            'name' => '没有找到相应记录，请重新搜索'
        ));
    }

    make_json_result($arr);
}elseif ($_REQUEST['act']=='add_cat_size'){
	 /* 检查权限 */
    check_authz_json('relevancy_cat_size');
    	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $json = new JSON;
    $cat_ids   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $size_id   = $arguments[0];
    $size_name = $db->getOne("SELECT size_name FROM " . $os->table('size') . " WHERE size_id='$size_id'");
    foreach ($cat_ids as $val){
	    $sql = "INSERT INTO " . $os->table('category_size') . " VALUES(null,'$val','$size_id','$size_name')";
	    $db->query($sql);
    }

    $arr = get_cat_sizelist($size_id);
    $opt = array();
    
    foreach ($arr AS $val)
    {
        $opt[] = array('value'     => $val['cat_id'],
                       'text'      => $val['cat_name'],
                       'data'      => '');
    }
    
    clear_cache_files();
    make_json_result($opt);
}elseif($_REQUEST['act']=='drop_cat_size'){
	 /* 检查权限 */
    check_authz_json('relevancy_cat_size');
    
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $json = new JSON;
    $cat_ids   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $size_id   = $arguments[0];
    $sql = "DELETE FROM " .$os->table('category_size') . " WHERE size_id='$size_id' AND " . db_create_in($cat_ids, "cat_id");
    $db->query($sql);

    $arr = get_cat_sizelist($size_id);
    $opt = array();
    
    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['cat_id'],
                       'text'       => $val['cat_name'],
                       'data'       => '');
    }
    
    clear_cache_files();
    make_json_result($opt);	
}

function get_sizelist(){
    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

        $filter['keyword']  = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);

        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }        
        
        if ($filter['keyword'])
        {
			$where .= " AND (size_code LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR size_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }         
        
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('size').' where 1 '.$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);    
        
        /* 查询记录 */
		$sql = "SELECT size_id,size_code,size_name,size_note FROM ". $GLOBALS['os']->table('size') .' where 1 '.$where." ORDER BY size_id DESC";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
    
    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $rows;
    }	
    
    return array('size' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function get_cat_sizelist($size_id=0){
	static $row = NULL;
	
	$sql = "SELECT c.cat_name,c.cat_id FROM ".$GLOBALS['os']->table('category_size').
	       " c_s LEFT JOIN ".$GLOBALS['os']->table('category')." c ON c_s.cat_id=c.cat_id";
	if($size_id>0){
		$sql .= " WHERE c_s.size_id = '$size_id'";
	}
	$sql .= " ORDER BY c_s.cat_size_id DESC";

	if ($row === NULL){
		$row = $GLOBALS['db']->getAll($sql);
	}
	return $row;		
}
?>